package com.xray.netdisk.utils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xray.netdisk.pojo.FileItem;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件工具类
 */
public class FileUtils {

    //服务器的IP
    public static final String IP = "127.0.0.1";
    //服务器的端口
    public static final int PORT = 8888;
    //服务器的上传目录
    public static final String UPLOAD_DIR = "D:\\upload";
    //客户端的下载目录
    public static final String DOWNLOAD_DIR = "D:\\download";
    //登录命令
    public static final int TYPE_LOGIN = 0;
    //查询命令
    public static final int TYPE_LIST = 1;
    //上传命令
    public static final int TYPE_UPLOAD = 2;
    //下载命令
    public static final int TYPE_DOWNLOAD = 3;
    //删除命令
    public static final int TYPE_DELETE = 4;

    /**
     * 获得上传目录中的文件列表
     * @return
     */
    public static List<FileItem> getFiles(){
        File file = new File(UPLOAD_DIR);
        //上传目录不存在，就创建目录，返回空
        if(!file.exists()){
            file.mkdir();
            return null;
        }
        //列举出目录中所有的文件，返回文件集合
        List<FileItem> fileList = new ArrayList<>();
        File[] files = file.listFiles();
        for(int i = 0;i < files.length;i++){
            File f = files[i];
            fileList.add(new FileItem(i+1L,f.getName(),f.getAbsolutePath(),f.length()));
        }
        return fileList;
    }

    /**
     * 将集合转换为JSON
     * @param items
     * @return
     */
    public static String listToJSON(List<FileItem> items){
        Gson gson = new Gson();
        return gson.toJson(items);
    }

    /**
     * 将JSON解析为集合
     * @param json
     * @return
     */
    public static List<FileItem> jsonToList(String json){
        Gson gson = new Gson();
        List<FileItem> list = gson.fromJson(json,new TypeToken<List<FileItem>>(){}.getType());
        return list;
    }

    /**
     * 读取输入流，写入到输出流
     * @param inputStream
     * @param outputStream
     * @throws IOException
     */
    public static void io(InputStream inputStream, OutputStream outputStream) throws IOException {
        byte[] buf = new byte[1024];
        int len = 0;
        while((len = inputStream.read(buf)) != -1){
            outputStream.write(buf,0,len);
        }
        inputStream.close();
        outputStream.close();
    }
}
